<template>
  <div class="app-container">
    <el-row>
      <!-- 区域数据 -->
      <el-col :xs="24" v-show="treeVisibale === true" class="tree_bg">
        <!-- <div>
          <el-input
            v-model="keyWordName"
            placeholder="输入关键字进行过滤"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div> -->
        <div class="head-container">
          <el-tree
            :data="areaOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
            v-loading="treeloading"
          />
        </div>
        <div class="tree_close" @click="changeTreeShow">
          <i class="el-icon-caret-left" style="color: white"></i>
        </div>
      </el-col>
      <el-col class="jiange"></el-col>
      <div class="tree_open" @click="changeTreeShow" v-show="treeVisibale === false">
        <i class="el-icon-caret-right" style="color: white"></i>
      </div>
      <el-col :xs="24" :class="treeVisibale ? 'table_small_bg' : 'table_big_bg'">
        <el-row class="line-bottom" v-show="showSearch">
          <el-col class="form_col">
            <el-form :model="queryParams" ref="queryForm" :size="size" v-show="showSearch" :label-width="labelWidth">
              <div id="searchFilter" style="display: flex; flex-wrap: wrap">
                <el-form-item label="区域名称" prop="areaName">
                  <el-input
                    v-model="queryParams.areaName"
                    placeholder="请输入区域名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
              </div>
            </el-form>
          </el-col>
          <el-col class="form_query">
            <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
            </el-button>
            <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
            <el-button @click="resetQuery" size="mini">重置</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8 padding_top_bottom">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['basedata:areas:add']"
            >新增</el-button>
          </el-col>
          <RightDropdown :columns="columns" :showSearch.sync="showSearch" @queryTable="getList" :exportdisabled="disabled"></RightDropdown>
        </el-row>

        <el-table v-loading="loading" :data="areasList" max-height="600" ref="table">
          <!-- <el-table-column type="selection" width="55" align="center" fixed/> -->
          <!-- <el-table-column label="租户ID" align="center" prop="tenant_id" v-if="false" :show-overflow-tooltip="true"/> -->
          <el-table-column label="区域名称" align="center" prop="areaName" v-if="columns[0].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="区域编码" align="center" prop="areaCode" v-if="columns[1].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="区域地址" align="center" prop="area_add" v-if="columns[2].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="区域描述" align="center" prop="details" v-if="columns[3].visible" :show-overflow-tooltip="true"/>
          <!-- <el-table-column label="备注" align="center" prop="remark" v-if="columns[5].visible" :show-overflow-tooltip="true"/> -->
          <!-- <el-table-column label="经度" align="center" prop="lng" v-if="columns[6].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="纬度" align="center" prop="lat" v-if="columns[7].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="经纬度" align="center" prop="locate" v-if="columns[8].visible" :show-overflow-tooltip="true"/> -->
          <el-table-column label="父级区域" align="center" prop="parentId" v-if="columns[4].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['basedata:areas:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['basedata:areas:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改区域对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :label-width="labelWidth" :inline="true">
        <!-- <el-form-item label="租户ID" prop="tenant_id">
          <el-input v-model="form.tenant_id" placeholder="请输入租户ID" />
        </el-form-item> -->
        <el-form-item label="归属水司" prop="tenant_id">
          <el-select v-model="form.tenant_id" placeholder="请选择归属水司" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.belong_department"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区域名称" prop="areaName">
          <el-input v-model="form.areaName" placeholder="请输入区域名称" />
        </el-form-item>
        <!-- <el-form-item label="区域编码" prop="areaCode">
          <el-input v-model="form.areaCode" placeholder="请输入区域编码" :disabled="true"/>
        </el-form-item> -->
        <el-form-item label="区域地址" prop="area_add">
          <el-input v-model="form.area_add" placeholder="请输入区域地址" />
        </el-form-item>
        <el-form-item label="区域描述" prop="details">
          <el-input v-model="form.details" type="textarea" placeholder="请输入内容" style="width: 202px;"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" style="width: 202px;"/>
        </el-form-item>
        <!-- <el-form-item label="经度" prop="lng">
          <el-input v-model="form.lng" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input v-model="form.lat" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="经纬度" prop="locate">
          <el-input v-model="form.locate" placeholder="请输入经纬度" />
        </el-form-item> -->
        <el-form-item label="父级区域" prop="parentId" v-if="title === '添加区域'">
          <treeselect v-model="form.parentId" :options="areasOptions" :normalizer="normalizer" placeholder="请选择父级区域" style="width: 202px;"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAreas, getAreas, delAreas, addAreas, updateAreas, getChildren } from "@/api/basedata/areas";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Areas",
  dicts: ['belong_department'],
  components: {
    Treeselect
  },
  data() {
    return {
      disabled: true,
      selectOptions:{},
      size:'small',
      collapseAble: false,
      fold: false,
      maxShow: '3',
      labelWidth: '90px',
      // 列信息
      columns: [
        // { key: 0, label: `租户ID`, visible: false },
        { key: 0, label: `区域名称`, visible: true },
        { key: 1, label: `区域编码`, visible: true },
        { key: 2, label: `区域地址`, visible: true },
        { key: 3, label: `区域描述`, visible: true },
        // { key: 5, label: `备注`, visible: true },
        // { key: 6, label: `经度`, visible: true },
        // { key: 7, label: `纬度`, visible: true },
        // { key: 8, label: `经纬度`, visible: true },
        { key: 4, label: `父级区域`, visible: false },
      ],
      defaultProps: {
        children: "children",
        label: "areaName",
        id: 'id'
      },
      AreaName:'',
      // 区域树选项
      areaOptions: [],
      // 区域名称
      keyWordName: '',
      // 树状态
      treeVisibale: true,
      // 遮罩层
      loading: true,
      treeloading: false,
      // 显示搜索条件
      showSearch: true,
      // 区域表格数据
      areasList: [],
      // 区域树选项
      areasOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        areaName: null,
        id: null,
      },
      // 总条数
      total: 0,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        tenant_id: [
          { required: true, message: "租户不能为空", trigger: "blur" }
        ],
        areaName: [
          { required: true, message: "区域名称不能为空", trigger: "blur" }
        ],
        area_add: [
          { required: true, message: "区域地址不能为空", trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "父级区域不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.queryParams.id = 0
  },
  mounted() {
    this.getAreaTree();
    this.getList();
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  },
  watch: {
    // 根据名称筛选区域树
    keyWordName(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.size}`)
      const len = group?.length ? group?.length - 1 : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.areaName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.areaName = null
      this.queryParams.id = data.id
      getChildren(this.queryParams).then(response => {
        this.areasList = response.rows
        this.loading = false;
      });
    },
    /** 查询区域下拉树结构 */
    getAreaTree() {
      this.treeloading = true
      this.areaOptions = [];
      const data = {};
      let list_ = JSON.parse(localStorage.getItem('list'))
      data.children = this.handleTree(list_, "id", "parentId");
      this.areaOptions.push(...data.children);
      this.treeloading = false
    },
    copyTree(list) {
      list.forEach((item) => {
        item.id = item.areaCode;
        item.label = item.areaName;
        item.children = item.children;
        if (item.children && item.children.length) {
          this.copyTree(item.children);
        }
      });
      return list;
    },
    // 改变tree的显示与隐藏
    changeTreeShow(){
      this.treeVisibale =!this.treeVisibale
    },
    /** 查询区域列表 */
    getList() {
      this.loading = true;
      if(this.queryParams.areaName != null){
        this.queryParams.id = null
      }
      getChildren(this.queryParams).then(response => {
        this.areasList = this.handleTree(response.rows,"id", "parentId");
        this.total = response.total
        this.loading = false;
      });
    },
    /** 转换区域数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.areaName,
        children: node.children
      };
    },
      /** 查询区域下拉树结构 */
    getTreeselect() {
      listAreas().then(response => {
        this.areasOptions = [];
        const data = { id: 0, areaName: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.areasOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        tenant_id: null,
        id: null,
        areaName: null,
        areaCode: null,
        area_add: null,
        details: null,
        remark: null,
        lng: null,
        lat: null,
        locate: null,
        parentId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.parentId = row.id;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加区域";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.parentId = row.parentId;
      }
      getAreas(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改区域";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.title === "修改区域") {
            updateAreas(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.queryParams.id = this.form.parentId
              getChildren(this.queryParams).then(response => {
                this.areasList = response.rows
                this.loading = false;
              });
              this.getAreaTree();
              this.open = false;
            });
          } else if(this.title === "添加区域"){
            addAreas(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.queryParams.id = this.form.parentId
              getChildren(this.queryParams).then(response => {
                this.areasList = response.rows
                this.loading = false;
              });
              this.getAreaTree();
              this.open = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除区域编号为"' + row.id + '"的数据项？').then(function() {
        return delAreas(row.id);
      }).then(() => {
        this.getList();
        this.getAreaTree();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
<style lang="scss" scoped>
.form_col{
    width: 80%;
    ::v-deep .el-form {
      width: 100%;
    }
    ::v-deep .el-form-item {
      width: 25%;
    }
  }
  .form_query{
    width: 20%;
    text-align: right;
  }
</style>
